package lol.clann.minecraft.springboot.plugin.core.service;

import com.ruoshui.utils.java.iterable.IterableUtils;
import lol.clann.minecraft.springboot.api.spi.ddl.DDL;
import lol.clann.minecraft.springboot.plugin.core.mapper.DDLMapper;
import lol.clann.minecraft.springboot.plugin.core.model.DDLVersion;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Map;

/**
 * 这个手动创建
 *
 * @author pyz
 * @date 2019/8/1 11:10 PM
 */
@Slf4j
@Component
@DependsOn("sqlSessionFactory")
@ConditionalOnProperty(name = "springbootplugin.datasource.enable", havingValue = "true")
public class DDLManager {

    @Autowired
    private DDLMapper mapper;
    @Autowired
    private DDLExecutor ddlExecutor;

    public void ddl() {
        //        首先创建sbp的表结构
        if (!mapper.tableExist("sbp_plugin_ddl")) {
            ddlExecutor.initSbpPlugin();
        }
        LOGGER.info("执行ddl: " + ddlExecutor.getDdlMap().keySet().toString());
        if (!ddlExecutor.getDdlMap().isEmpty()) {
            List<DDLVersion> ddlVersions = mapper.fetchDDlVersion(new HashSet<>(ddlExecutor.getDdlMap().keySet()));
            Map<String, DDLVersion> ddlVersionMap = IterableUtils.toMap(ddlVersions, i -> i.getPlugin());
            LOGGER.info("ddlVersionMap:" + ddlVersionMap.toString());
            for (String plugin : ddlExecutor.getDdlMap().keySet()) {
                ddlPlugin(plugin, ddlVersionMap);
            }
        }
        LOGGER.info("ddl执行完毕...");
    }

    private void ddlPlugin(String plugin, Map<String, DDLVersion> ddlVersionMap) {
        DDLVersion version = ddlVersionMap.get(plugin);
        if (version == null) {
            version = new DDLVersion();
            version.setPlugin(plugin);
            version.setVersion(Integer.MIN_VALUE);
        }
        List<DDL> ddls = ddlExecutor.getDdlMap().get(plugin);
        for (DDL ddl : ddls) {
            version = ddlExecutor.executeDDL(version, ddl);
        }
    }

}
